package com.summer.data.jql.builder;

import com.summer.data.Jsql;
import com.summer.data.dialect.Dialect;
import com.summer.data.jql.Context;
import com.summer.data.jql.JsqlAble;
import com.summer.data.jql.behavior.SelectAble;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author 345480567@qq.com
 */

public class SelectBuilder implements JsqlAble {

    public boolean distinct = false;

    public List<SelectAble> expList = new ArrayList<>();

    Context ctx;

    public SelectBuilder(Context ctx) {
        this.ctx = ctx;
    }

    public SelectBuilder distinct() {
        distinct = true;
        return this;
    }

    public void add(SelectAble... exps) {
        Collections.addAll(expList, exps);
    }

    @Override
    public Jsql buildJsql(Dialect dialect) {
        Jsql jsql = new Jsql();

        for (int i=0; i<expList.size(); i++) {
            SelectAble exp = expList.get(i);
            if (i==0) {
                jsql.append("SELECT ");
                if (distinct) {
                    jsql.append("DISTINCT ");
                }
            } else {
                jsql.append(", ");
            }

            Jsql expJsql = exp.toSelectJsql(ctx, dialect);
            jsql.append(expJsql);
        }
        jsql.append(System.lineSeparator());
        return jsql;
    }

}
